import Router from '@koa/router'
import User from '../models/User'
import { generateToken } from '../utils/token'

export const whoAmI: Router.Middleware = async (ctx) => {

    if (!ctx.state.user) {
        ctx.body = { success: false, msg: '未登录' }
        return
    }

    const { id } = ctx.state.user

    if (!id) {
        ctx.body = { success: false, msg: '参数错误' }
        return
    }

    try {
        const user = await User.findByPk(id, {
            attributes: {
                exclude: ['password', 'createdAt', 'updatedAt', 'deletedAt'],
            },
        })
        if (!user) {
            ctx.body = { success: false, msg: '获取用户信息失败' }
            return
        }
        ctx.body = { success: true, msg: '获取成功', data: user }
    } catch (error) {
        ctx.body = { success: false, msg: '发生错误' }
    }
}

export const loginController: Router.Middleware = async (ctx) => {
    const { username, password } = ctx.request.body

    if (!username || !password) {
        ctx.body = { success: false, msg: '参数错误' }
    }

    try {
        const user = await User.findOne({
            where: {
                userId: username,
                password,
            },
            attributes: {
                exclude: ['password', 'createdAt', 'updatedAt', 'deletedAt'],
            },
        })
        console.log(user)
        if (!user) {
            ctx.body = { success: false, msg: '用户名或密码错误' }
            return
        }
        ctx.body = {
            success: true,
            msg: '登录成功',
            data: {
                token: generateToken({
                    id: user.id,
                    userId: user.userId,
                    name: user.name,
                    role: user.role,
                }),
                userInfo: user,
            },
        }
    } catch (error) {
        ctx.body = { success: false, msg: '发生错误' }
    }
}
